<?php

class StaffController extends AppController
{
    # Controller Name to be used
    var $name = 'Staff';

    # Models to be used
    var $uses = array(
        'User','Project','Branch','Department','Group'
    );

    # set the layout to use
    var $layout = 'staff_layout';

    function  beforeFilter($moduleName = null){
        parent::beforeFilter();
    }

    function index($type = 'get'){

        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    $condition_array = array(
                        'User.deleted' => 'n',
                        'NOT'=>array('User.type'=>'Support')
                    );

                    if (!empty($search_query)) {
                        if ($qtype == 'username') {
                            $condition_array = array(
                                'User.name' => $search_query,
                                'User.deleted' => 'n'
                            );
                        }
                        elseif($qtype == 'fname') {
                            $condition_array = array(
                                'User.fname LIKE ' => $search_query.'%',
                                'User.deleted' => 'n'
                            );
                        }
                        elseif($qtype == 'mname') {
                            $condition_array = array(
                                'User.mname LIKE ' => $search_query.'%',
                                'User.deleted' => 'n'
                            );
                        }
                        elseif($qtype == 'lname') {
                            $condition_array = array(
                                'User.lname LIKE ' => $search_query.'%',
                                'User.deleted' => 'n'
                            );
                        }
                        elseif($qtype == 'email') {
                            $condition_array = array(
                                'User.email' => $search_query,
                                'User.deleted' => 'n'
                            );
                        }
                        elseif($qtype == 'fon_number') {
                            $condition_array = array(
                                'User.fon_number' => $search_query,
                                'User.deleted' => 'n'
                            );
                        }
                    }
                    $contain = array(
                        'Group'=>array('fields' => array('Group.id', 'Group.name')),
                        'Branch'=>array('fields' => array('Branch.id', 'Branch.name')),
                        'Department'=>array('fields' => array('Department.id', 'Department.name'))
                    );
                    $data_table = $this->User->find('all', array('conditions' => $condition_array, 'contain'=>$contain,'order' => "User.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => 1));
                    $data_table_count = $this->User->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['User']['id'],
                                'cell' => array(
                                    $obj['User']['id'],
                                    $obj['User']['fname'],
                                    $obj['User']['mname'],
                                    $obj['User']['lname'],
                                    $obj['User']['username'],
                                    $obj['User']['type'],
                                    $obj['User']['fon_number'],
                                    $obj['User']['email'],
                                    $obj['Group']['name'],
                                    $obj['Branch']['name'],
                                    $obj['Department']['name']
                                ),
                                'property'=>array(
                                    'bg_color'=>$obj['User']['row_bg_color']
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    }
                    else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }
                    break;

                case 'save' :
                    $data = array('User' => $_POST);
                    if ($_POST['id'] == 0) {//New user
                        $res = $this->User->validateUsername($_POST['username']);
                        if ($res) {
                            return json_encode(array('success' => 1, 'msg' => 'Username already exist.'));
                        }
                    }
                    $pass = '';
                    if ($_POST['id'] == 0) {
                        $pass = $this->randomString(6);
                        $data['User']['password'] = AuthComponent::password($pass);
                    }
                    if ($_POST['id'] > 0) {
                        $data['User']['modified_by'] = $this->authUser['id'];
                    } else {
                        $data['User']['created_by'] = $this->authUser['id'];
                    }

                    if ($this->User->save($data['User'])) {
                        if($_POST['id'] > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        }
                        else{ //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved! And the default password is '.$pass, 'id'=>$this->User->id));
                        }
                    } else {
                        return json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'reset_pass' :
                    $pass = $this->request->data['User']['password'];
                    if (empty($pass)) {
                        return json_encode(array('code' => 1, 'msg' => 'Please enter a password.'));
                    }
                    $this->request->data['User']['password'] = AuthComponent::password($pass);
                    $this->request->data['User']['modified_by'] = $this->authUser['id'];

                    if ($this->User->save($this->request->data)) {
                        return json_encode(array('code' => 0, 'msg' => 'Password have been reset!'));
                    } else {
                        return json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'delete':
                    $ids = $_POST['ids'];
                    $status = $_POST['status'];
                    if($status == 'disable'){
                        $change =  array('User.active' => "'n'",'User.row_bg_color' => "'tr_red'",'User.modified_by' => $this->authUser['id']);
                    }
                    else{
                        $change =  array('User.active' => "'y'",'User.row_bg_color' => "''",'User.modified_by' => $this->authUser['id']);
                    }
                    //We will disable rather than delete
                    $modObj = ClassRegistry::init('User');
                    $result = $modObj->updateAll(
                        $change,
                        array('User.id' => $ids)
                    );
                    if ($result) {
                        if($status == 'disable'){
                            return json_encode(array('code' => 0, 'msg' => 'Account(s) Disabled!'));
                        }
                        else{
                            return json_encode(array('code' => 0, 'msg' => 'Account(s) Enabled!'));
                        }

                    } else {
                        if($status == 'disable'){
                            return json_encode(array('code' => 1, 'msg' => 'Account(s) cannot be disabled.'));
                        }
                        else{
                            return json_encode(array('code' => 1, 'msg' => 'Account(s) cannot be enabled.'));
                        }

                    }
                break;

                case 'sub-load':
                    /** Loading */
                    $gdata = $this->User->getUserProjectById($_POST['id']);
                    $return_arr = array();
                    if($gdata){
                        foreach ($gdata['Project'] as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['UsersProject']['id'],
                                'cell' => array(
                                    $obj['name']
                                )
                            );
                        }
                        return json_encode(array('code' => 0, 'rows' => $return_arr));
                    }
                    else {
                        return json_encode(array('code' => 1, 'rows' => array(), 'mesg' => __('No Record Found')));
                    }
                    break;

                case 'sub-save' :
                    $res = $this->User->checkUsersProject($_POST['parent_id'],$_POST['project_id']);
                    if($res){
                        return json_encode(array('code' => 1, 'msg' => 'Record Already Exist.'));
                    }
                    $save = array(
                        'UsersProject'=>array(
                            'id'=>$_POST['id'],
                            'user_id'=>$_POST['parent_id'],
                            'project_id'=>$_POST['project_id']
                        )
                    );

                    $this->User->bindModel(array('hasMany' => array('UsersProject')));
                    $rest = $this->User->UsersProject->save($save);
                    if ($rest) {
                        if($_POST['id'] > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        }
                        else{ //If new pass back extra data if needed.
                            $new_id = $rest['UsersProject']['id'];
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved!', 'id'=>$new_id));
                        }
                    } else {
                        return json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'sub-delete' :
                    $ids = $_POST['ids'];
                    $result = $this->User->deleteUsersProject($ids);
                    if ($result) {
                        return json_encode(array('code' => 0, 'msg' => 'Data Deleted!'));
                    } else {
                        return json_encode(array('code' => 1, 'msg' => 'Data cannot be deleted'));
                    }
                    break;
            }
        }

        $branches = $this->getBranches();
        $departments = $this->getDepartments();
        $groups = $this->getGroups();
        $projects = $this->getProjects();
        $user_types = array();
        foreach($this->staff_types as $key => $value){
            $user_types[] = array(
                'id'=>$key,
                'name'=>$value
            );
        }

        $title_for_layout = 'Staff';
        $page_description = 'Setup And Manage Staff';
        $this->set(compact('title_for_layout','page_description','branches','departments','groups','projects','user_types'));
    }

}